package cn.xiehang.SoundSight;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Response;

public class RegisterPage extends AppCompatActivity {
    private EditText userName;
    private EditText passWord;
    private EditText passWordAgain;
    private EditText email;
    private EditText code;
    private Button registerButton;
    private Button registerVerifyButton;
    private Button showOrHidePassword;
    private Button showOrHidePasswordAgain;
    private OkHttpClient client;
    private ProgressDialog progressDialog;
    private String url = SeverURL.URL+"/register";
    private String url_code = SeverURL.URL+"/verify";


    private int countdownTime = -1; // 倒计时时间（秒）
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (countdownTime > 0) {
                countdownTime--;
                registerButton.setText(String.valueOf(countdownTime));
                handler.postDelayed(this, 1000); // 每秒更新一次
            }
            if (countdownTime == 0) {
                registerButton.setText("重新发送");
            }
        }
    };
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_main);
        // 初始化 ProgressDialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("请稍等片刻...");
        progressDialog.setCancelable(false);
        // 在 onCreate 中正确初始化视图元素
        registerButton = findViewById(R.id.registerButton);
        userName = findViewById(R.id.username);
        passWord = findViewById(R.id.register_password);
        passWordAgain = findViewById(R.id.register_confirmPassword);
        email = findViewById(R.id.email);
        code = findViewById(R.id.register_code);
        registerVerifyButton = findViewById(R.id.register_code_button);
        showOrHidePassword = findViewById(R.id.register_password_show_or_hide);
        showOrHidePasswordAgain = findViewById(R.id.register_password_confirm_show_or_hide);
        showOrHidePassword.setOnClickListener(v -> {
            // 处理按钮点击事件
            if (passWord.getInputType() == 129) {
                passWord.setInputType(128);
                showOrHidePassword.setBackground(getDrawable(R.drawable.show_password));
            } else {
                passWord.setInputType(129);
                showOrHidePassword.setBackground(getDrawable(R.drawable.hide_password));
            }
        });
        showOrHidePasswordAgain.setOnClickListener(v -> {
            // 处理按钮点击事件
            if (passWordAgain.getInputType() == 129) {
                passWordAgain.setInputType(128);
                showOrHidePasswordAgain.setBackground(getDrawable(R.drawable.show_password));
            } else {
                passWordAgain.setInputType(129);
                showOrHidePasswordAgain.setBackground(getDrawable(R.drawable.hide_password));
            }
        });



        registerButton.setOnClickListener(v -> {
            String username = userName.getText().toString();
            String password = passWord.getText().toString();
            String confirmPassword = passWordAgain.getText().toString();
            String email = this.email.getText().toString();

            if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() || email.isEmpty()) {
                // 如果用户名或密码为空，弹出提示
                Toast.makeText(RegisterPage.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!password.equals(confirmPassword)) {
                // 如果两次输入的密码不一致，弹出提示
                Toast.makeText(RegisterPage.this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                return;
            }
            //如果密码长度小于6，弹出提示
            if (password.length() < 6) {
                Toast.makeText(RegisterPage.this, "密码长度不能小于6", Toast.LENGTH_SHORT).show();
                return;
            }
            // 如果邮箱格式不正确，弹出提示
            //邮箱格式.在@后面
            if (!email.contains("@")) {
                Toast.makeText(RegisterPage.this, "邮箱格式不正确", Toast.LENGTH_SHORT).show();
                return;
            }
            // 显示 ProgressDialog
            progressDialog.show();

            register(username, password, email);



            // 点击按钮后，开始倒计时
            startCountdown();
        });
        registerVerifyButton.setOnClickListener(v -> {
            String code = this.code.getText().toString();
            String username = userName.getText().toString();
            String password = passWord.getText().toString();
            String email = this.email.getText().toString();
            if (code.isEmpty()) {
                // 如果验证码为空，弹出提示
                Toast.makeText(RegisterPage.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                return;
            }
            // 显示 ProgressDialog
            progressDialog.show();
            verify(code, username, password, email);
        });
    }
private void register(String username, String password, String email) {
    // 创建 OkHttpClient 实例
    OkHttpClient client = new OkHttpClient();

    // 创建 Gson 实例
    Gson gson = new Gson();

    // 创建一个 User 对象
    HashMap<String, String> postData = new HashMap<>();
    postData.put("username", username);
    postData.put("password", password);
    postData.put("email", email);

    // 将 User 对象转换为 JSON 字符串
    String json = gson.toJson(postData);

    // 创建一个 Request 对象
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(url)
            .post(okhttp3.RequestBody.create(json, okhttp3.MediaType.parse("application/json")))
            .build();
    client = new OkHttpClient();
    // 异步执行请求
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // 请求失败时，关闭弹窗
            runOnUiThread(() -> {
                progressDialog.dismiss();
                // 显示错误信息或其他操作
                Toast.makeText(RegisterPage.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                countdownTime = 5;
            });
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            //如果状态码是400，表示登录失败，将返回信息转化为json格式，并打印message
            if (response.code() == 400) {
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 显示错误信息或其他操作
                    String json = null;
                    try {
                        json = response.body().string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Gson gson = new Gson();
                    HashMap<String, String> map = gson.fromJson(json, HashMap.class);
                    String message = map.get("message");
                    Toast.makeText(RegisterPage.this, message, Toast.LENGTH_SHORT).show();
                    countdownTime = 5;
                    //如果message里面有未激活，显示验证码输入框
                    if(message.contains("未激活")){
                        code.setVisibility(View.VISIBLE);
                        registerVerifyButton.setVisibility(View.VISIBLE);
                    }
                });
            }
            else {
                // 注册成功
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    Toast.makeText(RegisterPage.this, "请查看邮箱验证码激活账号", Toast.LENGTH_SHORT).show();
                    //显示验证码输入框
                    code.setVisibility(View.VISIBLE);
                    registerVerifyButton.setVisibility(View.VISIBLE);
                });
            }
        }
    });
}
private void verify(String code, String username, String password, String email) {
    // 创建 OkHttpClient 实例
    OkHttpClient client = new OkHttpClient();

    // 创建 Gson 实例
    Gson gson = new Gson();

    // 创建一个 User 对象
    HashMap<String, String> postData = new HashMap<>();
    postData.put("code", code);
    postData.put("username", username);
    postData.put("password", password);
    postData.put("email", email);

    // 将 User 对象转换为 JSON 字符串
    String json = gson.toJson(postData);

    // 创建一个 Request 对象
    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(url_code)
            .post(okhttp3.RequestBody.create(json, okhttp3.MediaType.parse("application/json")))
            .build();

    // 发送请求并获取响应
    client = new OkHttpClient();
    // 异步执行请求
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // 请求失败时，关闭弹窗
            runOnUiThread(() -> {
                progressDialog.dismiss();
                // 显示错误信息或其他操作
                Toast.makeText(RegisterPage.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                countdownTime = 5;
            });
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            //如果状态码是400，表示登录失败，将返回信息转化为json格式，并打印message
            if (response.code() == 400) {
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 显示错误信息或其他操作
                    String json = null;
                    try {
                        json = response.body().string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Gson gson = new Gson();
                    HashMap<String, String> map = gson.fromJson(json, HashMap.class);
                    String message = map.get("message");
                    Toast.makeText(RegisterPage.this, message, Toast.LENGTH_SHORT).show();
                    countdownTime = 5;
                });
            }
            else {
                // 注册成功
                runOnUiThread(() -> {
                    progressDialog.dismiss();
                    // 显示错误信息或其他操作
                    Toast.makeText(RegisterPage.this, "激活成功", Toast.LENGTH_SHORT).show();
                    SharedPreferences sharedPref = getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putString("username", username);
                    editor.putString("password",password);
                    editor.putBoolean("is_logged_in", true);
                    editor.commit();
                    Intent intent = new Intent(RegisterPage.this, MainPage.class);
                    startActivity(intent);
                    finish();
                });
            }
        }
    });
}
    private void startCountdown() {
        countdownTime = 60; // 你可以设置任意倒计时时间
        registerButton.setText(String.valueOf(countdownTime));
        handler.post(runnable);
    }
}
